package ru.sanluck.tg.command;

import org.springframework.stereotype.Service;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.User;
import org.telegram.telegrambots.meta.bots.AbsSender;
import ru.sanluck.books.BookReadersService;
import ru.sanluck.lib.BookReader;
import ru.sanluck.tg.Dialog;
import ru.sanluck.tg.TgUser;
import ru.sanluck.tg.TgUserService;
import ru.sanluck.tg.UserMapper;

import java.util.Optional;
import java.util.Set;

@Service
public class Register extends AbsTgCommand {

    private static final String REGISTER = "/register";
    private static final String SPACE = " ";
    //TODO: локализация
    private static final String REGISTER_MESSAGE = "Укажите ваше имя и фамилию (через пробел)";
    private static final String INCORRECT_NAME = "Имя и фамилия указаны некорректно!";
    private static final String HELLO = "Добрый день, %s!";


    private final TgUserService tgUserService;
    private final BookReadersService bookReadersService;

    public Register(TgUserService tgUserService, UserMapper userMapper, TgUserService tgUserService1, BookReadersService bookReadersService) {
        super(tgUserService, userMapper);
        this.tgUserService = tgUserService1;
        this.bookReadersService = bookReadersService;
    }

    @Override
    public String commandText() {
        return REGISTER;
    }

    @Override
    public Set<Dialog> dialogs() {
        return Set.of(Dialog.START, Dialog.REGISTER);
    }

    @Override
    public void executeCommand(Message message, AbsSender sender) {
        User user = message.getFrom();
        if (checkRegisteredReader(message, sender)) {
            return;
        }

        TgUser tgUser = Optional
                .ofNullable(tgUserService.getUser(user.getUserName()))
                .orElse(createUser(user, Dialog.REGISTER));

        if (Dialog.START == tgUser.getDialog()) {
            sendTextMessage(message.getChatId(), REGISTER_MESSAGE, sender);
            tgUserService.changeDialog(user.getUserName(), Dialog.REGISTER);
            return;
        }

        if (message.isUserMessage()) {
            String messageText = message.getText();
            if (!checkFirstAndSecondName(messageText)) {
                sendTextMessage(message.getChatId(), INCORRECT_NAME, sender);
                throw new RuntimeException(INCORRECT_NAME);
            } else {
                registerBookReader(user, messageText);
                tgUserService.changeDialog(user.getUserName(), Dialog.SEARCH);
            }
        }
    }

    private boolean checkRegisteredReader(Message message, AbsSender sender) {
        User user = message.getFrom();
        BookReader reader = bookReadersService.getBookReader(user.getUserName());

        if (reader != null) {
            sendTextMessage(message.getChatId(), HELLO.formatted(reader.getSecondName() + SPACE + reader.getFirstName()), sender);
            tgUserService.changeDialog(user.getUserName(), Dialog.SEARCH);
            return true;
        }

        return false;
    }

    private void registerBookReader(User user, String message) {
        BookReader reader = bookReadersService.getBookReader(user.getUserName());
        if (reader == null) {
            String[] names = message.split(SPACE);
            bookReadersService.registerInLibrary(user.getUserName(), names[0], names[1]);
        }
    }

    private boolean checkFirstAndSecondName(String name) {
        if (name == null || name.isEmpty()) {
            return false;
        }

        if (!name.contains(SPACE)) {
            return false;
        }

        return name.split(SPACE).length >= 2;
    }
}
